package ldh.im.handle;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageCodec;
import ldh.im.dto.base.Dto;
import ldh.im.dto.base.ServerMessage;
import ldh.im.TransferData;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;

public class CToCoderHandler extends MessageToMessageCodec<TransferData, Dto> {

//    private static final Logger LOGGER = LoggerFactory.getLogger(CToCoderHandler.class);

    private ConcurrentHashMap<String, Consumer<? extends Dto>> callbackMap;
    private Consumer<Dto> serverConsumer;

    public CToCoderHandler(ConcurrentHashMap<String, Consumer<? extends Dto>> callbackMap, Consumer<Dto> serverConsumer) {
        this.callbackMap = callbackMap;
        this.serverConsumer = serverConsumer;
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, Dto msg, List<Object> out) throws Exception {
        TransferData transferData = new TransferData();
        transferData.setData(msg);
        out.add(transferData);
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, TransferData msg, List<Object> out) throws Exception {
        Dto dto = msg.getData();
        if (dto instanceof ServerMessage) {
            serverConsumer.accept(dto);
            return;
        }
        Consumer<Dto> consumer = (Consumer<Dto>) callbackMap.remove(dto.getLocalSeq());
        if (consumer != null) {
            consumer.accept(dto);
        } else {
//            LOGGER.warn("程序应该到不了这儿，可能是写的太多，丢掉了一些consumer。{}", JsonUtil.toJson(dto));
        }
    }
}
